// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/serializers/presto_serializer.h>
#include <pollux/serializers/vector_stream.h>
#include <pollux/vector/vector_stream.h>

namespace kumo::pollux::serializer::presto::detail {
    class PrestoIterativeVectorSerializer : public IterativeVectorSerializer {
    public:
        PrestoIterativeVectorSerializer(
            const RowTypePtr &rowType,
            int32_t numRows,
            StreamArena *streamArena,
            const PrestoVectorSerde::PrestoOptions &opts);

        void append(
            const RowVectorPtr &vector,
            const melon::Range<const IndexRange *> &ranges,
            Scratch &scratch) override;

        void append(
            const RowVectorPtr &vector,
            const melon::Range<const vector_size_t *> &rows,
            Scratch &scratch) override;

        size_t maxSerializedSize() const override;

        // The SerializedPage layout is:
        // numRows(4) | codec(1) | uncompressedSize(4) | compressedSize(4) |
        // checksum(8) | data
        void flush(OutputStream *out) override;

        std::unordered_map<std::string, RuntimeCounter> runtimeStats() override;

        void clear() override;

    private:
        const PrestoVectorSerde::PrestoOptions opts_;
        StreamArena *const streamArena_;
        const std::unique_ptr<melon::compression::Codec> codec_;

        int32_t numRows_{0};
        std::vector<VectorStream, memory::StlAllocator<VectorStream> > streams_;

        // Count of forthcoming compressions to skip.
        int32_t numCompressionToSkip_{0};
        CompressionStats stats_;
    };
} // namespace kumo::pollux::serializer::presto::detail
